package com.inspur.edp.bef.bemanager.util;

import com.inspur.edp.bef.bizentity.GspBizEntityObject;
import com.inspur.edp.bef.bizentity.GspBusinessEntity;
import com.inspur.edp.das.commonmodel.IGspCommonObject;
import com.inspur.edp.lcm.databaseobject.api.DatabaseObjectServiceForWebIde;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import io.iec.edp.caf.databaseobject.api.entity.AbstractDatabaseObject;
import io.iec.edp.caf.databaseobject.api.entity.DatabaseObjectTable;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Dbo相关操作
 * @author haoxiaofei
 */
public class DboUtil {
    protected static Logger logger = LoggerFactory.getLogger(DboUtil.class);

    /**
     * 循环执行删除dbo文件
     * 1、dbo文件中description中字段为“isSysGen”表示系统生成，可删除。
     * 2、只删除dbo文件
     *
     * @param dboIDs 要删除dbo文件的dboId集合
     * @param path 元数据路径
     */
    public static void dealDboFiles(List<String> dboIDs, String path) {
        if (dboIDs == null || path == null) {
            return;
        }
        DatabaseObjectServiceForWebIde dboService = SpringBeanUtils.getBean(DatabaseObjectServiceForWebIde.class);
        for (String dboID: dboIDs) {
            try {
                AbstractDatabaseObject dbo = dboService.getDatabaseObjectById(path, dboID);
                if (dbo instanceof DatabaseObjectTable) {
                    if (dbo.getDescription() != null && dbo.getDescription().contains("isSysGen")) {
                        if (dboService.isDatabaseObjectFileExist(path, dbo.getCode())) {
                            dboService.databaseObjectDelete(path, dbo.getCode());
                        }
                    }
                }
            } catch (Exception e) {
                logger.error("dbo删除失败，dboID：" + dboID, e);
            }
        }
    }


    /**
     * 获取业务实体的所有dbo ID
     *
     * @param be 业务实体
     * @return dbo ID
     */
    public static List<String> getDboIDs(GspBusinessEntity be) {
        List<String> dboIDs = new ArrayList<>();
        addDboIDByBeObj(be.getMainObject(), dboIDs);
        return dboIDs;
    }

    /**
     * 递归遍历所有节点
     *
     * @param beObject be节点
     * @param dboIDs 存Dbo ID
     */
    private static void addDboIDByBeObj(GspBizEntityObject beObject, List<String> dboIDs) {
        if (beObject == null) {
            return;
        }
        if (beObject.getRefObjectName() != null && !beObject.getRefObjectName().isEmpty()) {
            dboIDs.add(beObject.getRefObjectName());
        }
        if (beObject.getContainChildObjects() == null || beObject.getContainChildObjects().isEmpty()) {
            return;
        }
        for (IGspCommonObject beObj : beObject.getContainChildObjects()) {
            addDboIDByBeObj((GspBizEntityObject)beObj, dboIDs);
        }
    }
}
